package com.cai.service;

import com.cai.utils.RedisKey;
import com.cai.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.servlet.Servlet;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint(value = "/live/{roomId}/{userId}")
@Slf4j
public class BulletScreenService implements RedisKey {
    private static ApplicationContext applicationContext;
    private RedisTemplate<Serializable, Serializable> redisTemplate;
    private static Map<Session,String> sessionStringMap=new HashMap<>();
    private Session session;
    private String sessionId;
    private String userId;
    private String roomId;

    @OnOpen
    public void openConnection(Session session, @PathParam("roomId") String roomId, @PathParam("userId") String userId) {
        redisTemplate();
        this.sessionId = session.getId();
        this.session = session;
        this.userId = userId;
        this.roomId = roomId;
        sessionStringMap.put(session,userId);
        redisTemplate.opsForHash().put(SESSION, this.userId, sessionId);
        log.debug("用户 {} 加入连接", this.userId);
    }

    @OnClose
    public void closeConnection(Session session) throws IOException {
        redisTemplate.delete("message:");
        redisTemplate.opsForHash().delete(SESSION, userId);
        sessionStringMap.remove(session);
        log.debug("{} 断开连接", userId);
    }

    @OnMessage
    public void onMessage(String message) {
        redisTemplate.opsForValue().set("message:",message);
        log.info("收到客户端消息:" + message);
    }

    private void redisTemplate() {
        redisTemplate = (RedisTemplate<Serializable, Serializable>) SpringContextUtil.getBean("redisTemplate");
    }

    public String sendOneMessage(String userId, String message) {
        for (Map.Entry<Session, String> sessionStringEntry : sessionStringMap.entrySet()) {
            if (userId.equals(sessionStringEntry.getValue())){
                session=sessionStringEntry.getKey();
                session.getAsyncRemote().sendText(message);
                if (session.getId().equals(sessionId)) {
                    session.getAsyncRemote().sendText(message);
                    return "发送成功";
                }
            }
        }
        return "发送失败";
    }

    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }
}
